<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;

/**
 * 会员中心
 */
class Order extends Frontend
{

    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }


    /**
     * 买入
     */
    public function buy()
    {

        if ($this->request->isPost()) {


            $site = Config::get("site");
            if ($site['close_trading_system']==1) {
                $this->error('交易系统维护中。。。');
            }


            $code = $this->request->post("code");
            $money = $this->request->post("money");
            $pay_password = $this->request->post('pay_password');

            if ($this->auth->is_auth == 0) {
                $this->error(__('Not verify real name'), url('user/to_auth'));
                return false;
            }


            if ($money <= 0) {
                $this->error(__('amount can not be empty'), null, ['token' => $this->request->token()]);
                return false;
            }
            // 验证支付密码
            if (!$this->auth->checkpaypwd($pay_password)) {
                $this->error('支付密码不正确', null, ['token' => $this->request->token()]);
                return false;
            }
            // 存在未完成的委托
            $map = [
                'user_id' => $this->auth->id,
                // 'balance' => ['gt', 0],
                'status' => 0,
            ];
            $trade = db('trade')->where($map)->count();
            if ($trade > 0) {
                $this->error('当前委托尚未完成', null, ['token' => $this->request->token()]);
                return false;
            }

            $trade = model('trade');
            $data = [
                'user_id' => $this->auth->id,
                'market_price' => config('site.market_price'),
                'money' => $money,
                'balance' => $money,
            ];
            $ret = $trade->save($data);

           
            if ($ret) {
                model('trade')->autoMatch($trade->id);
                $this->success(__('Operation completed'), url('user/jiaoyi'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
    }

    /**
     * 卖出
     */
    public function sell()
    {

        if ($this->request->isPost()) {

            $site = Config::get("site");
            if ($site['close_trading_system']==1) {
                $this->error('交易系统维护中。。。');
            }
            
            $code = $this->request->post("code");
            $money = $this->request->post("money");
            $pay_password = $this->request->post('pay_password');

            if ($this->auth->is_auth == 0) {
                $this->error(__('Not verify real name'), url('user/to_auth'));
                return false;
            }

            if ($money <= 0) {
                $this->error(__('amount can not be empty'), null, ['token' => $this->request->token()]);
                return false;
            }
          
            // 收款信息
            $bank_info = [
                'alipay_account' => $this->auth->alipay_account,
                'wechat_account' => $this->auth->wechat_account,
                'alipay_pic'     => $this->auth->alipay_pic,
                'wechat_pic'     => $this->auth->wechat_pic,
            ];

            $bank_info = array_filter($bank_info);
            if (empty($bank_info)) {
                $this->error('请填写收款信息', url('user/shoukuan'));
                return false;
            }


            // 卖家扣除
            $sell_fee_rate = config('site.sell_fee');
            $sell_fee_rate = 0<$sell_fee_rate && $sell_fee_rate<1 ? $sell_fee_rate : 0;
            $sell_fee = $money*$sell_fee_rate;
            $total_money = $money+$sell_fee;
          
            // 余额不足
            if ($total_money > $this->auth->money) {
                $this->error(__('Insufficient Balance'), null, ['token' => $this->request->token()]);
                return false;
            }
            // 验证支付密码
            if (!$this->auth->checkpaypwd($pay_password)) {
                $this->error('支付密码不正确', null, ['token' => $this->request->token()]);
                return false;
            }
            // 存在未完成的委托
            $map = [
                'user_id' => $this->auth->id,
                // 'balance' => ['gt', 0],
                'status' => 0,
            ];
            $trade = db('trade')->where($map)->count();
            if ($trade > 0) {
                $this->error('当前委托尚未完成', null, ['token' => $this->request->token()]);
                return false;
            }

            // 收款信息
            // $authInfo = db('UserAuth')->where('user_id', $this->auth->id)->find();

            $data = [
                'user_id' => $this->auth->id,
                'type' => 1,
                'market_price' => config('site.market_price'),
                'money' => $money,
                'balance' => $money,
                'sell_fee_rate' => $sell_fee_rate,

                // 'real_name' => $authInfo['real_name'],
                // 'bank_name' => $authInfo['bank_name'],
                // 'branch_bank_name' => $authInfo['branch_bank_name'],
                // 'bank_card' => $authInfo['bank_card'],
            ];


            $trade = model('trade');
            $ret = $trade->save($data);
            if ($ret) {
              
                // model('user')->money($this->auth->id, -$sell_fee, 9, '扣除交易手续费');
              
                model('user')->moneyFrozen($this->auth->id, $total_money);
                model('trade')->autoMatch($trade->id);
                $this->success(__('Operation completed'), url('user/jiaoyi'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
    }

    // 打款
    public function pay()
    {
        $id = input('id');
        $map = [
            'buyer_id' => $this->auth->id,
            'status' => 1,
            'id' => $id,
        ];
        $order = model('order')->get($map);

        if ($this->request->isPost() && $order) {
            $image = $this->upload('image');         
 
            if (empty($image)) {
                $this->error('请上传打款截图');
            }

            $ret = $order->save(['image'=>$image, 'status'=>2, 'paytime'=>request()->time()]);
            if ($ret) {
                $this->success(__('Operation completed'), url('user/jiaoyi'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
    }

    // 确认收款
    public function done()
    {
        $id = input('id');
        $map = [
            'seller_id' => $this->auth->id,
            'status' => 2,
            'id' => $id,
        ];
        $order = model('order')->get($map);

        if ($this->request->isPost() && $order) {
            $post = input('post.');
            if (isset($post['no_pay'])) {
                $ret = $order->save(['status'=>5]);
                $this->success(__('Operation completed'), url('user/jiaoyi'));
            }
            $ret = $order->save(['status'=>3, 'finishtime'=>request()->time()]);
            if ($ret) {

                // 卖家扣除
                /*$sell_fee_rate = db('trade')->where('id', $order['seller_trade_id'])->value('sell_fee_rate');
                $frozen_money = $order['money']*(1+$sell_fee_rate);
                db('user')->where('id', $this->auth->id)->setDec('frozen_money', $frozen_money);*/

                //写入日志
                // model('MoneyLog')->create(['user_id' => $this->auth->id, 'money' => -$frozen_money, 'before' => $this->auth->money, 'after' => $this->auth->money, 'memo' => '交易完成', 'date' => date('Ymd'), 'type' => 8]);

                // 买家奖励
                /*$buy_fee = config('site.buy_fee');
                $buy_fee = 0<$buy_fee && $buy_fee<1 ? 1+$buy_fee : 1;
                model('user')->money($order['buyer_id'], $order['money']*$buy_fee, 7, '交易完成', $this->auth->id);


                model('trade')->checkStatus($order['buyer_trade_id']);
                model('trade')->checkStatus($order['seller_trade_id']);*/

                model('trade')->done($order);

                $this->success(__('Operation completed'), url('user/jiaoyi'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
    }

    // 取消
    public function cancel()
    {
        $id = input('id');
        $res = model('trade')->cancel($id, $this->auth->id);
        if ($res) {
            $this->success(__('Operation completed'), url('user/jiaoyi'));
        }else{
            $this->error(__('Operation failed'), null, ['token' => $this->request->token()]);
        }
    }


}
